package top.xchch.tool.cipher.atguigu;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

public class RsaDemo07 {
    public static void main(String[] args) throws Exception {
        String input = "硅谷";
        // 创建密钥对
        // KeyPairGenerator: 密钥对生成器
        String algorithm = "RSA";
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // 生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 获取公钥
        PublicKey publicKey = keyPair.getPublic();
        // 获取私钥
        PrivateKey privateKey = keyPair.getPrivate();
        // 获取公钥的字节数组
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // 获取私钥的字节数组
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // 使用base64进行编码
        String publicEncodeString = Base64.encode(publicKeyEncoded);
        String privateEncodeString = Base64.encode(privateKeyEncoded);
//        System.out.println("公钥: "+ publicEncodeString);
//        System.out.println("私钥: "+ privateEncodeString);

        // 私钥加密
        // 创建加密对象
        Cipher cipher = Cipher.getInstance(algorithm);
        // 对加密进行初始化
        // 第一个参数: 加密的模式
        // 第二个参数: 你想使用公钥加密还是私钥加密
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        // 使用私钥进行加密
        byte[] bytes = cipher.doFinal(input.getBytes()); // IllegalBlockSizeException: Data must not be longer than 245 bytes
        System.out.println(Base64.encode(bytes));

//        // 私钥解密   ×
//        cipher.init(Cipher.DECRYPT_MODE, privateKey);
//        byte[] bytes2 = cipher.doFinal(bytes);
//        System.out.println(new String(bytes2));

        // 公钥解密
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] bytes2 = cipher.doFinal(bytes);
        System.out.println(new String(bytes2));
    }
}
